<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="子任务名称" prop="subTaskName">
        <el-input
          v-model="queryParams.subTaskName"
          placeholder="请输入子任务名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="负责人姓名" prop="assigneeName">
        <el-input
          v-model="queryParams.assigneeName"
          placeholder="请输入负责人姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['task:subTask:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['task:subTask:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['task:subTask:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['task:subTask:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="subTaskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="子任务ID" align="center" prop="subTaskId" />
      <el-table-column label="所属主任务" align="center">
        <template slot-scope="scope">
          <el-tooltip :content="getMainTaskName(scope.row.mainTaskId)" placement="top">
            <span>{{ getMainTaskName(scope.row.mainTaskId) || scope.row.mainTaskId }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="子任务名称" align="center" prop="subTaskName" />
      <el-table-column label="子任务描述" align="center" prop="description" :show-overflow-tooltip="true" />
      <el-table-column label="负责人姓名" align="center" prop="assigneeName" />
      <el-table-column label="子任务状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sub_task_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['task:subTask:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['task:subTask:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-paperclip"
            @click="handleAttachment(scope.row)"
            v-hasPermi="['task:subTask:query']"
          >附件</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改子任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="所属主任务" prop="mainTaskId">
          <el-select v-model="form.mainTaskId" placeholder="请选择所属主任务">
            <el-option
              v-for="task in mainTaskList"
              :key="task.taskId"
              :label="task.taskName"
              :value="task.taskId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="子任务名称" prop="subTaskName">
          <el-input v-model="form.subTaskName" placeholder="请输入子任务名称" />
        </el-form-item>
        <el-form-item label="子任务描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入子任务描述" />
        </el-form-item>
        <el-form-item label="负责人" prop="assigneeId">
          <el-select v-model="form.assigneeId" placeholder="请选择负责人" @change="handleAssigneeChange">
            <el-option
              v-for="user in userList"
              :key="user.userId"
              :label="user.nickName"
              :value="user.userId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="子任务状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option
              v-for="dict in dict.type.sub_task_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 任务附件对话框 -->
    <el-dialog :title="'子任务附件 - ' + (form.subTaskName || '')" :visible.sync="attachmentOpen" width="800px" append-to-body>
      <task-attachment
        :task-id="form.subTaskId"
        :task-type="1"
        :disabled="!form.subTaskId"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="attachmentOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSubTask, getSubTask, delSubTask, addSubTask, updateSubTask } from "@/api/task/subTask"
import { listUser } from "@/api/system/user"
import { listMaintask } from "@/api/task/maintask"
import TaskAttachment from "@/components/TaskAttachment"

export default {
  name: "SubTask",
  components: {
    TaskAttachment
  },
  dicts: ['sub_task_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 子任务表格数据
      subTaskList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        subTaskName: null,
        assigneeName: null,
      },
      // 表单参数
      form: {},
      // 用户列表
      userList: [],
      // 主任务列表
      mainTaskList: [],
      // 表单校验
      rules: {
        mainTaskId: [
          { required: true, message: "所属主任务ID不能为空", trigger: "blur" }
        ],
        subTaskName: [
          { required: true, message: "子任务名称不能为空", trigger: "blur" }
        ],
      },
      originalStatus: null,
      selectedTaskId: null,
      selectedTaskType: null,
      attachmentOpen: false
    }
  },
  created() {
    this.getList()
    this.getUserList()
    this.getMainTaskList()
  },
  methods: {
    /** 获取用户列表 */
    getUserList() {
      listUser().then(response => {
        this.userList = response.rows
      })
    },
    /** 获取主任务列表 */
    getMainTaskList() {
      listMaintask().then(response => {
        this.mainTaskList = response.rows
      })
    },
    /** 查询子任务列表 */
    getList() {
      this.loading = true
      listSubTask(this.queryParams).then(response => {
        this.subTaskList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        subTaskId: null,
        mainTaskId: null,
        subTaskName: null,
        description: null,
        assigneeId: null,
        assigneeName: null,
        status: 0,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.subTaskId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 负责人选择变化 */
    handleAssigneeChange(userId) {
      const user = this.userList.find(u => u.userId === userId)
      if (user) {
        this.form.assigneeName = user.nickName
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加子任务"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const subTaskId = row.subTaskId || this.ids
      getSubTask(subTaskId).then(response => {
        this.form = response.data
        this.originalStatus = response.data.status
        this.open = true
        this.title = "修改子任务"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const isStatusChange = this.form.subTaskId && this.originalStatus !== undefined && this.originalStatus !== this.form.status;
          
          if (this.form.subTaskId != null) {
            updateSubTask(this.form).then(response => {
              if (isStatusChange) {
                this.$modal.msgSuccess(`修改成功，子任务状态已从"${this.getStatusLabel(this.originalStatus)}"变更为"${this.getStatusLabel(this.form.status)}"`);
              } else {
                this.$modal.msgSuccess("修改成功");
              }
              this.open = false;
              this.getList();
              // 后端已经自动更新主任务状态，无需前端再次调用
            }).catch(error => {
              this.$modal.msgError("修改失败");
              console.error('子任务修改失败:', error);
            });
          } else {
            addSubTask(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              // 后端已经自动更新主任务状态，无需前端再次调用
            }).catch(error => {
              this.$modal.msgError("新增失败");
              console.error('子任务新增失败:', error);
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const subTaskIds = row.subTaskId || this.ids
      const mainTaskId = row.mainTaskId // 保存主任务ID用于后续更新
      this.$modal.confirm('是否确认删除子任务编号为"' + subTaskIds + '"的数据项？').then(function() {
        return delSubTask(subTaskIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
        // 后端已经自动更新主任务状态，无需前端再次调用
      }).catch(error => {
        if (error !== 'cancel') {
          this.$modal.msgError("删除失败")
          console.error('子任务删除失败:', error)
        }
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('task/subTask/export', {
        ...this.queryParams
      }, `subTask_${new Date().getTime()}.xlsx`)
    },
    /** 获取主任务名称 */
    getMainTaskName(mainTaskId) {
      const task = this.mainTaskList.find(t => t.taskId === mainTaskId)
      return task ? task.taskName : null
    },
    getStatusLabel(status) {
      const dict = this.dict.type.sub_task_status.find(d => d.value === status.toString())
      return dict ? dict.label : status
    },
    handleTaskAttachment(taskId, taskType) {
      this.selectedTaskId = taskId
      this.selectedTaskType = taskType
    },
    handleAttachment(row) {
      this.form = row
      this.attachmentOpen = true
    }
  }
}
</script>
